package cn.itcast.dao.impl;

import cn.itcast.dao.OrdersDao;
import cn.itcast.domain.Orders;
import cn.itcast.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrdersDaoimpl implements OrdersDao {
    private Connection conn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;

    //一丶查询所有订单信息
    public List<Orders> findAll() {

        //创建list集合,用于存储订单对象
        List<Orders> lis = new ArrayList<Orders>();

        try {
            //1.获取连接
            conn = JDBCUtil.getConn();
            //2.编写sql,获取预编译对象
            String sql = "select * from orders";
            ps = conn.prepareStatement(sql);
            //3.获取结果集
            rs = ps.executeQuery();

            while (rs.next()){
                Orders od = new Orders(rs.getInt(1),rs.getString(2),rs.getInt(3));
                lis.add(od);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //4.释放资源
            JDBCUtil.close(conn,ps,rs);
        }

        return lis;
    }

    //添加订单
    public void add(Orders od) {
        try {
            //1.获取连接
            conn = JDBCUtil.getConn();
            //2.编写sql,并创建预编译对象
            String sql = "insert into orders values(?,?,?)";
            ps = conn.prepareStatement(sql);
            //2.1添加数据,并执行
            ps.setInt(1,od.getId());
            ps.setString(2,od.getNumber());
            ps.setInt(3,od.getUid());
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            JDBCUtil.close(conn,ps);
        }

    }
}
